package com.sohu.peak.util;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import org.apache.struts2.ServletActionContext;

import com.sohu.peak.gallery.domain.Constants;

public class ImagicThread {
	private static final Logger log = new Logger();

	private class ImgMagic extends Thread {
		BufferedImage image;
		int maxHeight;
		int maxWidth;
		String oldPicPath;
		String newPicPath;
		boolean wmk;
		String wmloc;
		String wmtnp;
		
		public ImgMagic(BufferedImage image, int maxWidth, int maxHeight,
				String oldPicPath, String newPicPath, boolean wmk,
				String wmloc, String wmtnp){
			this.image=image;
			this.maxHeight=maxHeight;
			this.maxWidth=maxWidth;
			this.oldPicPath=oldPicPath;
			this.newPicPath=newPicPath;
			this.wmk=wmk;
			this.wmloc=wmloc;
			this.wmtnp=wmtnp;
		}
		
		public void run() {
			try {

				Process px;
				String command;
					command = "/usr/local/bin/convert -strip -sample " + maxWidth
							+ " -border 1 -bordercolor black " + oldPicPath + " " + newPicPath;

				px = Runtime.getRuntime().exec(command);
				log.debug(command);
				px.waitFor();

				checkFileSize();

			} catch (IOException e) {
				e.printStackTrace();
				log.error("rebuildPic error:" + e);
			} catch (InterruptedException e) {
				e.printStackTrace();
				log.error("rebuildPic error:" + e);
			}
		}
		
		public void checkFileSize() throws IOException,InterruptedException {
			File file = new File(oldPicPath);
            if (file.exists()) {
                int quality = 100;
                //if(file.length()>12000){
                while (file.length() > 12000) {
                    quality = quality - 20;
                    if (quality < 10)
                        break;
                    Process px;
                    String command;
                    command = "/usr/local/bin/convert -strip -sample " + maxWidth + 
                    	" -border 1 -bordercolor black -quality " + quality + " " + oldPicPath + " " + newPicPath;
					px = Runtime.getRuntime().exec(command);
					log.debug(command);
					px.waitFor();
                    
                    file = new File(newPicPath);
                }
            }
		}
	}

	public Thread getThread(BufferedImage image, int maxHeight, int maxWidth,
			String oldPicPath, String newPicPath, boolean wmk,
			String wmloc, String wmtnp) {
		return new ImgMagic( image,  maxHeight, maxWidth, oldPicPath, newPicPath, wmk,wmloc,wmtnp);
	}

}
